package fule.com.playandroidkotlin.base

import com.google.gson.JsonParseException
import fule.com.kotlindemo.base.BaseView
import fule.com.playandroidkotlin.ui.view.BannerView
import io.reactivex.observers.DisposableObserver
import org.json.JSONException
import retrofit2.HttpException
import java.io.InterruptedIOException
import java.net.ConnectException
import java.net.UnknownHostException
import java.text.ParseException

/**
 * 作者： njb
 * 时间： 2016/12/27.13:56
 * 描述：
 * 来源：
 */
abstract class BaseObserver<T> : DisposableObserver<T> {
    protected var view: BaseView?
    private var isShowDialog = false

    constructor(view: BannerView?) {
        this.view = view
    }

    constructor(view: BaseView?) {
        this.view = view
    }

    override fun onStart() {
        if (view != null && isShowDialog) {
            view!!.showLoading()
        }
    }

    override fun onNext(o: T) {
        try {
            val model = o as Model
            if (model.errorCode == 0) {
                onSuccess(o)
            } else {
                if (view != null) {
                    view!!.onErrorCode(model)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            onError(e.toString())
        }
    }

    override fun onError(e: Throwable) {
        if (view != null && isShowDialog) {
            view!!.hideLoading()
        }
        if (e is HttpException) {
            //   HTTP错误
            onException(BAD_NETWORK)
        } else if (e is ConnectException
                || e is UnknownHostException) {
            //   连接错误
            onException(CONNECT_ERROR)
        } else if (e is InterruptedIOException) {
            //  连接超时
            onException(CONNECT_TIMEOUT)
        } else if (e is JsonParseException
                || e is JSONException
                || e is ParseException) {
            //  解析错误
            onException(PARSE_ERROR)
        } else {
            onError(e.toString())
        }
    }

    private fun onException(unknownError: Int) {
        when (unknownError) {
            CONNECT_ERROR -> onError("连接错误")
            CONNECT_TIMEOUT -> onError("连接超时")
            BAD_NETWORK -> onError("网络问题")
            PARSE_ERROR -> onError("解析数据失败")
            else -> {
            }
        }
    }

    override fun onComplete() {
        if (view != null && isShowDialog) {
            view!!.hideLoading()
        }
    }

    abstract fun onSuccess(o: T)
    abstract fun onError(msg: String?)

    companion object {
        /**
         * 解析数据失败
         */
        const val PARSE_ERROR = 1001

        /**
         * 网络问题
         */
        const val BAD_NETWORK = 1002

        /**
         * 连接错误
         */
        const val CONNECT_ERROR = 1003

        /**
         * 连接超时
         */
        const val CONNECT_TIMEOUT = 1004
    }
}